﻿using System;
using System.Collections.Generic;
using System.IO;

namespace Nutilities.Net.Binary.Extensions
{
    public static class BinaryReaderExtensions
    {
        public static T ReadReadable<T>(this BinaryReader reader)
            where T : IReadable, new()
        {
            T readable = new T();
            readable.ReadFrom(reader);
            return readable;
        }

        public static List<T> ReadList<T>(this BinaryReader reader)
            where T : IReadable, new()
        {
            int capacity = reader.ReadInt32();
            List<T> list = new List<T>(capacity);
            for (int i = 0; i < capacity; i++)
            {
                list.Add(reader.ReadReadable<T>());
            }
            return list;
        }

        public static Dictionary<TKey, TValue> ReadDictionary<TKey, TValue>(this BinaryReader reader)
            where TKey : IReadable, new()
            where TValue : IReadable, new()
        {
            int capacity = reader.ReadInt32();
            Dictionary<TKey, TValue> dictionary = new Dictionary<TKey, TValue>(capacity);
            for (int i = 0; i < capacity; i++)
            {
                dictionary.Add(reader.ReadReadable<TKey>(), reader.ReadReadable<TValue>());
            }
            return dictionary;
        }

        public static DateTime ReadDateTime(this BinaryReader reader)
        {
            return DateTime.FromBinary(reader.ReadInt64());
        }

        public static TimeSpan ReadTimeSpan(this BinaryReader reader)
        {
            return TimeSpan.FromTicks(reader.ReadInt64());
        }
    }
}
